// 引入封装好的请求方法
import { getInfoApi, loginApi } from "@/api/user/user";
// 引入返回值的类型
import { Result } from "@/http/request"
// 引入请求参数的类型
import { LoginParm } from "@/api/user/UserModel";
// 引入泛型
import { ActionContext } from "vuex";
// 引入根文件的state类型
import { RootState } from "..";
import { setUserId, setToken, setExpireTime } from "@/utils/auth"

export type UserState = {
  token: string,
  uesrId: string,
  permissions: string[]
}

export const state: UserState = {
  token: '',
  uesrId: '',
  permissions: []
}

export const mutations = {
  setToken(state: UserState, token: string) {
    state.token = token
  },
  setUserId(state: UserState, userId: string) {
    state.uesrId = userId
  },
  setRoles(state: UserState, val: string[]) {
    state.permissions = val
  }
}

// 异步操作
export const actions = {
  // 异步操作的action的固定写法，需要ActionContext和对应的state的类型声明
  // 如果是有分路由的，需要分路由的声明和总路由的声明
  login({ commit }: ActionContext<UserState, RootState>, loginParm: LoginParm) {
    return new Promise<Result>((resolve, reject) => {
      loginApi(loginParm).then(res => {
        if (res.data.code === 200) {
          commit('setToken', res.data.token)
          commit('setUserId', res.data.id)
          setUserId(res.data.id)
          setToken(res.data.token)
          setExpireTime(res.data.expireTime)
        }
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  getInfo({ commit }: ActionContext<UserState, RootState>) {
    return new Promise((resolve, reject) => {
      getInfoApi().then(res => {
        if (res.code === 200) {
          commit('setRoles', res.data.roles)
        }
        resolve(res.data)
      }).catch((error) => {
        reject(error)
      })
    })
  }
}

export const getters = {
  getToken(state: UserState) {
    return state.token
  },
  getPermissions(state:UserState){
    return state.permissions
}
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}